var app = getApp();
Page({
  data: {
    orderList: []
  },
  onLoad(options) {
    console.log('userId:', app.globalData.user.id);
    this.getOrderList();
  },
  
  // 获取订单列表
  getOrderList() {
    let userId = app.globalData.user.id;
    //console.log("用户ID：", userId);
    const requestUrl = app.globalData.baseUrl + '/sysOrder/Orderlist';
    //console.log("请求URL：", requestUrl);
    wx.request({
      url: app.globalData.baseUrl + '/sysOrder/Orderlist',
      data: { userId: userId },
      success: (res) => {
        //console.log("接口返回数据：", res.data);
        if (res.data.code === 200) {
          const orderList = res.data.data.map(order => {
            // 增强解析逻辑
            if (order.goodsInfo && order.goodsInfo.trim() !== '') {
              try {
                // 检查是否是有效的JSON格式
                if (order.goodsInfo.trim().startsWith('[') || order.goodsInfo.trim().startsWith('{')) {
                  order.goodsList = JSON.parse(order.goodsInfo);
                  //console.log("解析成功的商品列表：", order.goodsList);
                  
                  // 验证解析后的数据结构
                  if (order.goodsList && order.goodsList.length > 0) {
                    console.log("第一个商品详情：", order.goodsList[0]);
                    console.log("商品价格类型：", typeof order.goodsList[0].goodsPrice);
                    console.log("商品数量类型：", typeof order.goodsList[0].goodsNum);
                  }
                } else {
                  console.warn("goodsInfo不是有效的JSON格式：", order.goodsInfo);
                  order.goodsList = [];
                }
              } catch (e) {
                console.error("解析goodsInfo失败：", e, "错误的goodsInfo内容：", order.goodsInfo);
                order.goodsList = [];
              }
            } else {
              console.warn("goodsInfo为空");
              order.goodsList = [];
            }
            order.formattedTime = this.formatTime(order.creatTime);
            return order;
          });
          this.setData({ orderList }, () => {
            console.log("页面数据更新完成，当前订单数量：", this.data.orderList.length);
            if (this.data.orderList.length > 0) {
              console.log("第一个订单的完整数据：", this.data.orderList[0]);
            }
          });
        } else {
          console.error("接口返回错误：", res.data.msg);
          wx.showToast({ title: '获取订单失败', icon: 'error' });
        }
      },
      fail: (err) => {
        console.error("请求失败：", err);
        wx.showToast({ title: '网络错误', icon: 'error' });
      }
    });
  },
  // 格式化时间方法
formatTime(timestamp) {
    if (!timestamp) return '未知时间';
    
    try {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
      return '时间解析失败';
    }
  },
  // 创建订单
  createOrder() {
    let userId = app.globalData.user.id;
    wx.showLoading({ title: '创建订单中...' });
    
    wx.request({
      url: app.globalData.baseUrl + '/sysOrder/create',
      method: 'POST',
      data: { userId: userId },
      success: (res) => {
        wx.hideLoading();
        console.log("创建订单返回:", res.data);
        if (res.data.code === 200) {
          wx.showToast({ title: '订单创建成功' });
          // 刷新订单列表
          this.getOrderList();
        } else {
          wx.showToast({ title: res.data.msg || '创建失败', icon: 'error' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({ title: '网络错误', icon: 'error' });
      }
    });
  },
  
  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
});